import time

import pandas


class CSV():

    @staticmethod
    def save(rnt_list, csv_name='out'):
        '''
        code_list: [('id', 'num'), ('1', 'a'), ('2', 'b'), ('3', 'c')]
        '''
        csv_name = f'{csv_name} {int(time.time())} .csv'

        # 表头
        title = rnt_list[0]
        rnt_list = rnt_list[1:]

        # 结果
        rows = []
        for row in rnt_list:
            # rows.append([str(cell) + '\t' for cell in list(row)])
            # rows.append([cell for cell in list(row)])
            rows.append([f'="{cell}"' for cell in list(row)])

        data_frame = pandas.DataFrame(rows, columns=title)
        # qouting: 1-表示使用双引号(")引用所有字段, 建议 None
        data_frame.to_csv(csv_name, quoting=None, index=False, header=True, encoding='utf_8')

        # data_frame.to_csv(csv_name, quoting=csv.QUOTE_NONE, sep='，', index=False, encoding='utf_8')

    @staticmethod
    def save_batch(rnt_list, csv_name='out'):
        max_len = 1000000
        if len(rnt_list) >= max_len:
            rnt_list_head = rnt_list[0:1]
            for i in range(1, len(rnt_list), max_len):
                rnt_list_sub = rnt_list[i:i + max_len]
                CSV.save(rnt_list_head + rnt_list_sub, csv_name + str(i / max_len))

    @staticmethod
    def export_from_fetchall(rnt_head, rnt_list, csv_name=None):
        """
        :param rnt_head: 表头 cursor.description
        :param rnt_list 结果 cursor.fetchall()
        :param csv_name 文件名
        """

        csv_name = '{} {} .csv'.format(csv_name if csv_name is not None else 'CSV', round(time.time() * 1000))

        # 表头
        title = [col[0] for col in rnt_head]

        # 结果
        rows = []
        for row in rnt_list:
            # rows.append([str(cell) + '\t' for cell in list(row)])
            rows.append([cell for cell in list(row)])

        data_frame = pandas.DataFrame(rows, columns=title)
        data_frame.to_csv(csv_name, quoting=1, index=False, encoding='utf_8')
        return csv_name

    if __name__ == '__main__':
        CSV.save([(1, 2, 3), (2, 3, 4)])

    def export_2_csv(description, fetchall, csv_description=None):
        """
        导出为 csv 的函数
        :param description: 表头 cursor.rnt_head
        :param fetchall 结果 cursor.code_list()
        """
        dateformat = '%y%m%d_%H%M%S'
        csv_name = '{}{} {} .csv'.format(
            csv_description, '' if csv_description is not None else '',
            time.strftime(dateformat, time.localtime(time.time()))
        )

        # 表头
        title = [each[0] for each in description]

        # 查询结果
        rows = []
        for each in fetchall:
            each = [str(cell) + '\t' for cell in list(each)]
            rows.append(each)

        # 保存成 dataframe
        data_frame = pandas.DataFrame(rows, columns=title)
        # 保存成 csv: 这个编码是为了防止中文没法保存, line_num=None 的意思是没有行号
        data_frame.to_csv(csv_name, quoting=1, index=None, encoding='utf_8')
        # data_frame.to_csv(csv_file, quoting=None, line_num=None, encoding='utf_8')
        return csv_name
